const path = require('path')
const express = require('express')

// 跨域中间件
const cors = require('cors')
// 中间件，用于处理 multipart/form-data 类型的表单数据，用于上传文件
const multer = require('multer')

const app = express()
const port = 3000

const uploadPath = path.resolve(__dirname, "./uploads")

const storage = multer.diskStorage({
    // 保存路径
    destination: function (req, file, callback) {
        // 需要绝对路径
        callback(null, uploadPath)
    },
    // 保存的文件名
    filename: function (req, file, callback) {
        const filename = req.headers['x-file-name']
        callback(null, `${Date.now()}-${decodeURIComponent(filename)}`)
    },
})
const upload = multer({ storage })

app.use(cors())

// upload.single('file')接受一个以file命名的文件，信息保存在req.file
app.post('/upload', upload.single('file'), (req, res) => {
    console.log('file', req.file);
    res.json({
        url: `http://localhost:3000/uploads/${req.file.filename}`
    })
})

app.use('/uploads', express.static(uploadPath))

app.listen(port, () => {
    console.log(`server listening on port ${port}`);
})
